package com.xc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.dao.SysUserMapper;
import com.xc.pojo.LoginUser;
import com.xc.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 为springsecurity 提供 用户
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);

        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        if (sysUser==null){
            throw new RuntimeException("用户不存在");
        }

        // 查权限信息
        List<String> permissions = sysUserMapper.findPermissionsById(sysUser.getId());

        // LoginUser  继承了  UserDetails
        LoginUser loginUser = new LoginUser(sysUser,permissions);

        return loginUser;
    }
}
